package io.zhiller.storagedemo.storage.vm

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.asLiveData
import androidx.lifecycle.viewModelScope
import io.zhiller.storagedemo.storage.domain.Note
import io.zhiller.storagedemo.storage.repo.NoteRepo
import io.zhiller.storagedemo.storage.vm.states.NoteState
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import org.koin.core.KoinApplication.Companion.init

class NoteVM(
  private val noteRepo: NoteRepo
) : ViewModel() {

  private val _state = MutableStateFlow(NoteState())
  private val _notes = noteRepo.getAllNotes()
  val state = combine(_state, _notes) { state, notes ->
    state.copy(notes = notes)
  }.stateIn(
    viewModelScope,
    SharingStarted.WhileSubscribed(5000),
    NoteState()
  )

  fun getNotes() = viewModelScope.launch {
    noteRepo.getAllNotes().collectLatest {
      _state.update { it.copy(notes = it.notes) }
    }
  }

  fun upsertNote(note: Note) = viewModelScope.launch {
    noteRepo.upsertNote(note)
  }

  fun deleteNote(note: Note) = viewModelScope.launch {
    noteRepo.deleteNote(note)
  }
}